# coding=utf-8
# 防止中文乱码
import json
import pymysql
from common.utils.predefined import conf

class DBHelper:
  def __init__(self):
    # 建立数据库连接
    self.connect = pymysql.Connect(
      host=conf['dbconf']['host'],
      port=conf['dbconf']['port'],
      user=conf['dbconf']['user'],
      passwd=conf['dbconf']['passwd'],
      db=conf['dbconf']['db'],
      charset=conf['dbconf']['charset'],
      cursorclass=pymysql.cursors.DictCursor
    )
    # 获取游标
    self.cursor = self.connect.cursor()

  def close(self):
    # 关闭cursor
    self.cursor.close()
    # 关闭connection
    self.connect.close()

  def selectHelper(self, sql):
    try:
      print(sql)
      self.cursor.execute(sql)
      result = self.cursor.fetchall()
    except Exception as e:
      print("SQL error: {0}".format(e))
      self.close()
      raise NameError('SqlError')
    else:
      self.close()
      return result

  def selectOneHelper(self, sql):
    try:
      print(sql)
      self.cursor.execute(sql)
      result = self.cursor.fetchone()
    except Exception as e:
      print("SQL error: {0}".format(e))
      self.close()
      raise NameError('SqlError')
    else:
      self.close()
      return result

  def transactionHelper(self, *param):
    try:
      for sql in param:
        print(sql)
        self.cursor.execute(sql)
      self.connect.commit()
      result = self.cursor.fetchall()
    except Exception as e:
      print("SQL error: {0}".format(e))
      self.connect.rollback()
      self.close()
      raise NameError('SqlError')
    else:
      self.close()
      return result
